//引入express模块
const express = require('express')
//创建路由器对象
const router = express.Router()
//引入连接池模块
const pool = require('../pool.js')

//暴露路由器对象
module.exports = router

// 获取用户的详细信息
router.get('/user_detail', (req, res) => {
    pool.query('select * from user_detail', (err, r) => {
        if (err) {
            throw err
        }
        console.log(r)
        if (r.length == 0) {
            res.send({ code: 400, msg: '查询失败',data:r })
        } else {
            res.send({ code: 200, msg: '查询成功',data:r })
        }
    })
})
// 后台更新用户的详细信息
router.put('/user_change', (req, res, next) => {
	//获取put传递的参数
	var obj = req.body
	console.log(obj)
	pool.query('update user_detail set ? where id=?', [obj,obj.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.changedRows == 1) {
			res.send({ code: 200, msg: '修改成功' })
		} else {
			res.send({ code: 400, msg: '修改失败' })
		}
	})
})
// 后台删除用户的详细信息
router.delete('/:id', (req, res, next) => {
	pool.query('delete from user_detail where id=?', [req.params.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.affectedRows == 0) {
			res.send({ code: 400, msg: '删除失败' })
		} else {
			res.send({ code: 200, msg: '删除成功' })
		}
	})
})

// 用户登录
router.post('/login', (req, res) => {
	var obj = req.body
	console.log(obj)
	pool.query('select * from user_detail where username=? && password=?', [obj.username, obj.password], (err,
		r) => {
		if (err) {
			throw err
		}
		console.log(r)
		if (r.length == 0) {
			res.send({
				code: 400,
				msg: '登录失败'
			})
		} else {
			res.send({
				code: 200,
				msg: '登陆成功'
			})
		}
	})
})

// 用户注册
router.post('/register', (req, res, next) => {
	let username = req.body.username
	var obj = req.body


	let sql = 'select count(id) as count from user_detail where username=?'

	pool.query(sql, username, (err, r) => {
		if (err) {
			throw err
		}
		let count = r[0].count
		if (count == 0) {
			sql = 'insert into user_detail set?'
			pool.query(sql, [obj], (err, r) => {
				if (err) {
					throw err
				}
				res.send({ code: 200, msg: '注册成功' })
			})
		} else {
			res.send({ code: 401, msg: '注册失败,用户名已经存在' })
		}
	})
})